//
//  HomeTableViewController.swift
//  SinaWeibo
//
//  Created by yang on 15/11/8.
//  Copyright © 2015年 yang. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
private let HomeCellId = "HomeCellId"
class HomeTableViewController: BaseTableViewController {

    private lazy var  statuses = [Status]()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if  !userLogin{
            visitorLoginView?.setUIInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        prepareTableView()
        loadData()
    }
    @objc private func loadData(){
        //获取当前登录用户及其所关注用户的最新微博
        var since_id = 0
        var max_id = 0
        if indicatorView.isAnimating(){
            //上来刷新
             since_id = 0
             max_id = statuses.last?.id ?? 0
        }else{
            //下拉刷新
             max_id = 0
             since_id = statuses.first?.id ?? 0
        }
        
        StatusListViewModel().loadData(since_id:since_id,max_id:max_id) { (array) -> () in
            self.refreshControl?.endRefreshing()
        if array == nil {
            SVProgressHUD.showErrorWithStatus(AppErrorTip)
            self.indicatorView.stopAnimating()
            return
        }
            if since_id > 0 {
             //下拉
             self.statuses = array! + self.statuses
            }else if max_id > 0{
               self.statuses = self.statuses + array!
               self.indicatorView.stopAnimating()
            }else{
              self.statuses = array!
            }
        
        self.tableView.reloadData()

        }
        
    }
    private lazy var indicatorView:UIActivityIndicatorView = {
      let indicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    return indicator
    }()
    private func prepareTableView(){
        refreshControl = UIRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents:.ValueChanged)
    tableView.registerClass(StatusCell.self, forCellReuseIdentifier: HomeCellId)
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = .None
        tableView.tableFooterView = indicatorView
    }
}
extension HomeTableViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int  {
         return statuses.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellId, forIndexPath: indexPath) as! StatusCell
        cell.status = statuses[indexPath.row]
        if indexPath.row == statuses.count - 1 && !indicatorView.isAnimating(){
            indicatorView.startAnimating()
            loadData()
        }
        return cell
    }
}